package com.yonyou.crm.sys.quartz.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.quartz.rmitf.IDispatchTaskRmService;
import com.yonyou.crm.sys.quartz.ventity.DispatchGroupVO;
import com.yonyou.crm.sys.quartz.ventity.DispatchTaskVO;

@RestController
@RequestMapping(value = "/quartz/tasks")
public class DispatchTaskCtrl {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IDispatchTaskRmService taskService;

	/**
	 * 查询任务列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Integer page = (Integer) paramObj.get("page") == null ? 1 : (Integer) paramObj.get("page");
		Integer pageSize = (Integer) paramObj.get("pageSize") == null ? 10 : (Integer) paramObj.get("pageSize");
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>) paramObj
				.get("searchMap");

		if (page == null) {
			throw new CrmMessageException("page不能为空");
		}

		if (pageSize == null) {
			throw new CrmMessageException("pageSize不能为空");
		}

		Page<DispatchTaskVO> taskPage = taskService.selectTask(
				new Page<DispatchTaskVO>(page, pageSize), searchMap);

		return ResponseUtil.getObject(taskPage);
	}

	/**
	 * 任务详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}

		return ResponseUtil.getObject(
				taskService.getVOById(new DispatchTaskVO(), id));
	}

	/**
	 * 新增任务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object addTask(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		@SuppressWarnings({ "unused", "rawtypes" })
		Map retMap = new HashMap();
		DispatchTaskVO taskVO = RequestUtil
				.getVO(request, DispatchTaskVO.class);
		taskVO = taskService.saveDispatchTaskVO(taskVO);
		if (taskVO.getId() == null) {
			logger.error("taskVO.getId()为空");
			throw new CrmMessageException("获取自增主键为空");
		}
		return ResponseUtil.getObject(taskVO);
	}

	/**
	 * 修改任务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object editTask(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}
		DispatchTaskVO taskVO = RequestUtil
				.getVO(request, DispatchTaskVO.class);

		if (taskVO == null) {
			throw new CrmMessageException("转换实体失败");
		}
		taskService.updateDispatchTaskVO(taskVO);
		return ResponseUtil.getObject(
				getOperAfterData(id,request));
	}

	/**
	 * 删除任务 1、首要是先删除quartz对应的表 2、删除dispatch对应的task数据 3、删除任务日志
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}
		JSONObject paramObj = RequestUtil.getParamObject(request);
		int page = paramObj.getInt("page");
		int pageSize = paramObj.getInt("pageSize");
		@SuppressWarnings("unchecked")
		Map<String, Object> paraMap = (Map<String, Object>) paramObj
				.get("searchMap");
		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		taskService.deleteTask(id, new Page<DispatchTaskVO>(page, pageSize) ,
				paraMap);
		return ResponseUtil.getObject(taskService.selectTask(new Page<DispatchTaskVO>(page, pageSize), paraMap));
	}

	/**
	 * 停启用用户
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/state", method = RequestMethod.PUT)
	public Object updateEnableStatus(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}

		Integer enableStatus = (Integer) RequestUtil.getObject(request,
				"enableStatus");

		if (enableStatus == null) {
			throw new CrmMessageException("停启用状态不能为空");
		}
		taskService.updateEnableStatus(id, enableStatus);
		
		return ResponseUtil.getObject(getOperAfterData(id,request));
	}

	/**
	 * 立即启动
	 */
	@RequestMapping(value = "{id}/triggerJob", method = RequestMethod.PUT)
	public Object triggerJob(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}

		Integer enableStatus = (Integer) RequestUtil.getObject(request,
				"enableStatus");
		if (enableStatus == 1) {
			throw new CrmMessageException("停用状态不能立即执行");
		}
		taskService.triggerTask(id);
		return ResponseUtil.getObject(getOperAfterData(id,request),"立即执行成功");
	}
	private Page<DispatchTaskVO> getOperAfterData(String id,HttpServletRequest request) throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		Integer page = (Integer) paramObj.get("page") == null ? 1 : (Integer) paramObj.get("page");
		Integer pageSize = (Integer) paramObj.get("pageSize") == null ? 10 : (Integer) paramObj.get("pageSize");

		if (page == null) {
			throw new CrmMessageException("page不能为空");
		}

		if (pageSize == null) {
			throw new CrmMessageException("pageSize不能为空");
		}
		Map<String,Object> searchMap = new HashMap<String, Object>();
		searchMap.put("id", id);
		Page<DispatchTaskVO> taskPage = taskService.selectTask(
				new Page<DispatchTaskVO>(page, pageSize), searchMap);
		return taskPage;
	}
	/**
	 * 任务日志
	 */
	@RequestMapping(value = "{id}/taskLogDetail", method = RequestMethod.PUT)
	public Object taskLogDetail(@PathVariable("id") String id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}
		return ResponseUtil.getObject(
				taskService.getTaskLogDetail(id));
	}
	// 参照列表
	@RequestMapping(value = "ref", method = RequestMethod.GET)
	public Object getRefList(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		if (paramObj != null) {
			// 有分页信息返回分页列表
			if (paramObj.containsKey(HttpKeyConstant.Page)
					&& paramObj.containsKey(HttpKeyConstant.PageSize)) {
				return ResponseUtil.getObject(taskService.getRefPage(
						getRequestPage(paramObj), null));
			}
		}
		List<DispatchGroupVO> voList = taskService.getRefList(new HashMap<String, Object>());
		Page<DispatchGroupVO> page = new Page<DispatchGroupVO>();
		page.setData(voList);
		return ResponseUtil.getObject(page);
	}
	// 获取分页信息
	private Page<DispatchGroupVO> getRequestPage(JSONObject paramObj)
			throws CrmMessageException {
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		if (page == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError,
					"page不能为空");
		}
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError,
					"pageSize不能为空");
		}
		return new Page<DispatchGroupVO>(page, pageSize);
	}

}
